package com.example.demo.controller;

import com.example.demo.entity.SseEmitterUTF8;
import com.example.demo.listener.MyEvent;
import com.example.demo.service.SseService;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;


import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@RestController
public class SseController {

    @Resource
    private SseService service;
    @Resource
    private ApplicationEventPublisher eventPublisher;


    @GetMapping(value = "test/{clientId}", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitterUTF8 test(@PathVariable("clientId") String clientId) {
        String uuid = UUID.randomUUID().toString();
        SseEmitterUTF8 emitter = service.getConn(clientId,uuid);
        CompletableFuture.runAsync(() -> {
            try {
                emitter.send("创建连接");
            } catch (Exception e) {
                throw new RuntimeException("推送数据异常");
            }
        });

        return emitter;
    }

    @GetMapping("closeConn/{clientId}")
    public String closeConn(@PathVariable("clientId")String clientId) {
        service.closeConn(clientId);
        return "连接已关闭";
    }

    @GetMapping("push/{clientId}")
    public void push(@PathVariable("clientId")String clientId,@RequestParam String param) {
        eventPublisher.publishEvent(new MyEvent(clientId,param));
    }
}